

import 'package:auto_route/auto_route.dart';
import 'package:casdon/app/config/theme/theme_extention.dart';
import 'package:casdon/build_gen/assets.gen.dart';
import 'package:casdon/common/widget/badge_icon.dart';
import 'package:casdon/common/widget/common_app_bar.dart';
import 'package:flutter/material.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
import 'package:casdon/modules/me/application/notification/service_process_notifier.dart';
import 'package:casdon/modules/me/data/api/service_order_api.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
@RoutePage()
class ServiceOrderDetailScreen extends ConsumerWidget {
  final ServiceOrder? order;
  const ServiceOrderDetailScreen({super.key, required this.order});

  @override
  Widget build(BuildContext context, WidgetRef ref) {
    return Scaffold(
      appBar: CommonAppBar(title: "服务详情"),
      body: SingleChildScrollView(
        padding:  EdgeInsets.only(top: 10.h, bottom: 10.h),
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            // 服务内容区块
            _buildSectionWithTitle(
              iconPath: Assets.images.icServiceContent.path,
              title: '服务内容',
              children: [
                _buildInfoRow('工单号', order?.orderNumber ?? '-', context),
                _buildInfoRow('创建时间', order?.createTime ?? '-', context),
                _buildInfoRow('服务类型', order?.serviceType ?? '-', context),
                _buildInfoRow('设备型号', order?.product.productName ?? '-', context),
                _buildInfoRow('联系方式', '${order?.customerName ?? ''} ${order?.contactPhone ?? ''}', context),
                _buildInfoRow('期待服务时间', order?.expectTime ?? '-', context) ,
                _buildInfoRow('服务地址', order?.serviceAddress ?? '-', context),
                _buildInfoRow('反馈内容', order?.feedbackContent ?? '-', context, isLast: true),
              ],
            ),

             

            // 最新进展区块
            _buildSectionWithTitle(
              iconPath: Assets.images.icServiceProcess.path,
              title: '最新进展',
              children: [
                _buildProcessList(context, ref),
              ],
            ),
          ],
        ),
      ),
    );
  }

  Widget _buildSectionWithTitle({
    required String iconPath,
    required String title,
    required List<Widget> children,
  }) {
    return Container(
      decoration: BoxDecoration(
        color: const Color(0xFFFFFFFF), // 与卡片相同背景色
        borderRadius: BorderRadius.circular(8),
      ),
      margin: const EdgeInsets.only(bottom: 16), // 与下一个区块的间距
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          // 标题部分（带内边距）
          Padding(
            padding: const EdgeInsets.fromLTRB(16, 16, 16, 8),
            child: Row(
              children: [
                BadgeIcon(imagePath: iconPath),
                const SizedBox(width: 12),
                Text(
                  title,
                  style: const TextStyle(
                    fontSize: 16,
                    fontWeight: FontWeight.bold,
                    color: Colors.black,
                  ),
                ),
              ],
            ),
          ),

          // 内容部分（移除卡片原有背景）
          Padding(
            padding: const EdgeInsets.fromLTRB(16, 0, 16, 16),
            child: Column(children: children),
          ),
        ],
      ),
    );
  }

  // 信息行组件
  Widget _buildInfoRow(String label, String value, BuildContext context, {bool isLast = false}) {
    const double labelColumnWidth = 80; // 与右侧保持固定对齐
    const double gap = 10; // 与右侧内容间距 10

    return Column(
      children: [
        Row(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            SizedBox(
              width: labelColumnWidth,
              child: Text(
                label,
                style:  context.textTheme.bodyMedium?.copyWith(
                    color: context.customColorThemeNonNull.textColor2,
                  ),
              ),
            ),
            const SizedBox(width: gap),
            Expanded(
              child: Align(
                alignment: Alignment.centerLeft,
                child: Text(
                  value,
                  textAlign: TextAlign.left,
                  style: context.textTheme.bodyMedium?.copyWith(
                    color: context.customColorThemeNonNull.textColor1,
                  ),
                ),
              ),
            ),
          ],
        ),
        if (!isLast) const SizedBox(height: 12),
      ],
    );
  }

  // 进度列表（使用 Notifier 请求并填充）
  Widget _buildProcessList(BuildContext context, WidgetRef ref) {
    final asyncValue = ref.watch(serviceProcessNotifierProvider(order?.reqId ?? ''));
    return asyncValue.when(
      loading: () =>  Padding(
        padding: EdgeInsets.all(16.w),
        child: Center(child: CircularProgressIndicator(strokeWidth: 2)),
      ),
      error: (_, __) =>  Padding(
        padding: EdgeInsets.all(16.w),
        child: Text('加载失败'),
      ),
      data: (entities) {
        if (entities.isEmpty) {
          return  Padding(
            padding: EdgeInsets.all(16.w),
            child: Text('暂无进展'),
          );
        }
        // 按时间倒序（最新在上）排序
        final sorted = [...entities];
        int _cmp(a, b) {
          DateTime _parse(String s) {
            // 优先使用格式化时间；若为空用原始 createdon
            final str = (s);
            return DateTime.tryParse(str) ?? DateTime.fromMillisecondsSinceEpoch(0);
          }
          final ta = _parse(a.formattedCreatedOn.isNotEmpty ? a.formattedCreatedOn : (a.createdon ?? ''));
          final tb = _parse(b.formattedCreatedOn.isNotEmpty ? b.formattedCreatedOn : (b.createdon ?? ''));
          return tb.compareTo(ta); // 倒序
        }
        sorted.sort(_cmp);

        return Column(
          children: [
            for (int i = 0; i < sorted.length; i++)
              Padding(
                padding: EdgeInsets.only(bottom: i == sorted.length - 1 ? 0 : 12.h),
                child: _buildProcessInfoRow(
                  context,
                  '${sorted[i].formattedType} ${sorted[i].formattedCreatedOn}',
                  sorted[i].subject ?? '',
                  isLast: i == sorted.length - 1,
                ),
              ),
          ],
        );
      },
    );
  }

  Widget _buildProcessInfoRow(
    BuildContext context,
    String label,
    String value, {
    bool isLast = false,
  }) {
    return IntrinsicHeight(
      child: Row(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          // 左侧时间轴
          Row(
            children: [
              SizedBox(width: 10.w),
                 Column(
            children: [
              SizedBox(height: 7.h),
              CircleAvatar(
                radius: 3.w,
                backgroundColor: context.colorScheme.primary,
              ),
              SizedBox(height: 8.h),
              Expanded(
                child: Container(
                  width: 1.5.w,
                  color: isLast ? Colors.transparent : Color(0xFFDCDCDC),
                ),
              ),
               SizedBox(height: 3.h),
            ],
          ),
            ],
          ),
         

           SizedBox(width: 16.w),
          // 右侧内容
          Expanded(
            child: Column(
              crossAxisAlignment: CrossAxisAlignment.start,
              children: [
                Text(label, style: context.textTheme.bodyLarge?.copyWith(
                  color: context.colorScheme.primary,
                )),
                SizedBox(height: 4.h),
                Text(value, softWrap: true, style: context.textTheme.bodySmall?.copyWith(
                  color: context.customColorThemeNonNull.textColor2,
                )),
              ],
            ),
          ),
        ],
      ),
    );
  }
}
